#include "verifydcm.h"
#include "global.h"

#include <QFile>
#include <QTextStream>
#include <QTimer>
#include <QCoreApplication>

VerifyDcm::VerifyDcm(QObject *parent) : QObject(parent)
{

}

void VerifyDcm::fetchFile()
{
    QString file;
    gVerifyMutex.lock();
    if (gVerifyList.isEmpty())
        gVerifyCond.wait(&gVerifyMutex);
    file = gVerifyList.takeFirst();
    gVerifyMutex.unlock();
    verifyDcm(file);
    QTimer::singleShot(0, this, SLOT(fetchFile()));
}

void VerifyDcm::verifyDcm(const QString &file)
{
    QString f = file;
    QString suffix;
    f = f.mid(f.lastIndexOf("/")+1);

    int dotIdx = f.lastIndexOf(".");
    if (dotIdx >= 0)
        suffix = f.mid(dotIdx+1);

    if (passSuffix.contains(suffix, Qt::CaseInsensitive)) {
        appendParse(file);
    } else if ((!denySuffix.contains(suffix, Qt::CaseInsensitive)) || suffix.isEmpty()) {
        QFile dev(file);
        bool pass = false;
        if (dev.open(QIODevice::ReadOnly) && dev.seek(128)) {
            if (dev.read(4) == "DCIM") {
                appendParse(file);
                pass = true;
            }
        }
        dev.close();

        if (!suffix.isEmpty()) {
            QFile sdev;
            if (pass) {
                sdev.setFileName(QCoreApplication::applicationDirPath()+"/"DCM_PASS_SUFFIX_LIST_FILE);
                passSuffix += suffix;
            } else {
                sdev.setFileName(QCoreApplication::applicationDirPath()+"/"DCM_DENY_SUFFIX_LIST_FILE);
                denySuffix += suffix;
            }
            if (sdev.open(QIODevice::Append|QIODevice::Text)) {
                QTextStream out(&sdev);
                out << suffix << endl;
                sdev.close();
            }
        }
    }
}

void VerifyDcm::appendParse(const QString &file)
{
    gParseMutex.lock();
    gParseList.append(file);
    gParseCond.wakeAll();
    gParseMutex.unlock();
}
